package com.cmpe.group6.storyroad;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;

import com.cmpe.group6.storyroad.jsonClasses.Results;
import com.google.gson.Gson;

/**
 * Represents an asynchronous Get Locations task for getting all locations
 * from the server for autocompletion mechanism.
 * 
 */
public class LocationTask extends AsyncTask<Void, Void, String> {

	@Override
	protected String doInBackground(Void... params) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Utils.SERVER_NAME + "GetLocations");
		String jsonResponse = null;
		try {
			// Add your data
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs
					.add(new BasicNameValuePair("request_type", "Android"));
			nameValuePairs.add(new BasicNameValuePair("query", ""));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httppost);

			jsonResponse = EntityUtils.toString(response.getEntity());

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}

		return jsonResponse;

	}

	@Override
	protected void onPostExecute(final String response) {

		if (response != null) {

			Gson gson = new Gson();

			Results results = gson.fromJson(response, Results.class);

			Utils.locations = results.getResults();
		}
	}

	@Override
	protected void onCancelled() {

	}
}